<?php

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, true);
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('getallheaders')) {
    function getallheaders()
    {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

if (!function_exists('dd')) {
    function dd($data)
    {
        echo '<pre>';
        var_dump($data);
        die;
    }
}

/**
 * 生成uuid
 *
 * @return string
 */
if (!function_exists('uuid')) {
    function uuid()
    {
        mt_srand(( double )microtime() * 10000);
        $charid = strtoupper(md5(uniqid(rand(), true))); //根据当前时间（微秒计）生成唯一id.
        $hyphen = chr(45); // "-"
        $uuid = '' . substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);

        return $uuid;
    }
}

/**
 * 生成唯一标识符
 *
 * @return string
 */
if (!function_exists('unique')) {
    function unique()
    {
        mt_srand(( double )microtime() * 10000);
        return strtoupper(uniqid() . substr(md5(uniqid(rand(), true)), mt_rand(1, 29), 3));
    }
}

if (!function_exists('make_code')) {
    function make_code()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d') . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));

        //0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
        // 123456789ABCDEFGH JKLMN PQRSTUVWXY
        //0 I O Z
        for (
            $a = md5($rand, true),
            $s = '123456789ABCDEFGHJKLMNPQRSTUVWXY',
            $d = '',
            $f = 0;
            $f < 5;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;
        return $d;
    }
}

/**
 * 生成唯一id
 */
if (!function_exists('guid')) {
    function guid($factor = '', $prefix = '', $suffix = '')
    {
        list($usec, $sec) = explode(" ", microtime());
        $guid = $prefix . $factor . $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']
            . $sec . $usec
            . mt_rand(0, 1000000) . time() . mt_rand(0, 1000000) . $suffix;
        $guid = substr(sha1($guid), 8, 32);
        $guid = base_convert($guid, 16, 36);
        return $prefix . $guid . $suffix;
    }
}

/**
 * @param $time_type 1今天 2昨天 3本周 4上周 5近7天 6本月 7上月 8近30天 9本季度 10上季度 11本年 12上年
 * @param bool $timestamp_flag
 * @return array
 */
if (!function_exists('get_time')) {
    function get_time($time_type, $timestamp_flag = false)
    {
        date_default_timezone_set('PRC');
        switch ($time_type) {
            case '1':
                //今天
                $start_time = $timestamp_flag ? strtotime(date("Y-m-d 00:00:00")) : date("Y-m-d 00:00:00");
                $end_time = $timestamp_flag ? time() : date("Y-m-d H:i:s");
                break;
            case '2':
                //昨天
                $start_time = $timestamp_flag ? strtotime(date("Y-m-d 00:00:00")) - 86400 : date('Y-m-d 00:00:00', strtotime('-1 day'));
                $end_time = $timestamp_flag ? strtotime(date("Y-m-d 00:00:00")) - 1 : date('Y-m-d 23:59:59', strtotime('-1 day'));
                break;
            case '3':
                //本周
                $start_time = $timestamp_flag ? mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")) : date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
                $end_time = $timestamp_flag ? time() : date("Y-m-d H:i:s");
                //$end_time   = $timestamp_flag ? mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")) : date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
                break;
            case '4':
                //上周
                $start_time = $timestamp_flag ? mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y')) : date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y")));
                $end_time = $timestamp_flag ? mktime(23, 59, 59, date("m"), date("d") - date("w") + 7 - 7, date("Y")) : date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7 - 7, date("Y")));
                break;
            case '5':
                //近7天
                $start_time = $timestamp_flag ? strtotime('-7 day') : date('Y-m-d H:i:s', strtotime('-7 day'));
                $end_time = $timestamp_flag ? time() : date("Y-m-d H:i:s");
                break;
            case '6':
                //本月
                $start_time = $timestamp_flag ? strtotime(date("Y-m-01 00:00:00", time())) : date("Y-m-01 00:00:00", time());
                $end_time = $timestamp_flag ? time() : date("Y-m-d H:i:s");
                //$end_time   = $timestamp_flag ? strtotime(date("Y-m-t 23:59:59")) : date("Y-m-t 23:59:59");
                //$end_time   = $timestamp_flag ? mktime(23,59,59,date("m"),date("t"),date("Y")) : date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
                break;
            case '7':
                //上月
                //$start_time = $timestamp_flag ? mktime(0, 0 , 0,date("m")-1,1,date("Y")) : date("Y-m-d H:i:s", mktime(0, 0 , 0,date("m")-1,1,date("Y")));
                //$end_time   = $timestamp_flag ? mktime(23,59,59,date("m") ,0,date("Y")) : date("Y-m-d H:i:s", mktime(23,59,59,date("m") ,0,date("Y")));
                $start_time = $timestamp_flag ? strtotime(date("Y-m-01 00:00:00", strtotime("-1 month"))) : date("Y-m-01 00:00:00", strtotime("-1 month"));
                $end_time = $timestamp_flag ? strtotime(date("Y-m-t 23:59:59", strtotime("-1 month"))) : date("Y-m-t 23:59:59", strtotime("-1 month"));
                break;
            case '8':
                //近30天
                $start_time = $timestamp_flag ? strtotime('-30 day') : date('Y-m-d H:i:s', strtotime('-30 day'));
                $end_time = $timestamp_flag ? time() : date("Y-m-d H:i:s");
                break;
            case '9':
                //本季度
                $season = ceil(date("n") / 3); //获取月份的季度
                $start_time = $timestamp_flag ? mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')) : date('Y-m-01 H:i:s', mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')));
                $end_time = $timestamp_flag ? mktime(23, 59, 59, $season * 3, 1, date('Y')) : date('Y-m-t H:i:s', mktime(23, 59, 59, $season * 3, 1, date('Y')));
                break;
            case '10':
                //上季度
                $season = ceil(date("n") / 3); //获取月份的季度
                $start_time = $timestamp_flag ? mktime(0, 0, 0, ($season - 2) * 3 + 1, 1, date('Y')) : date('Y-m-01 H:i:s', mktime(0, 0, 0, ($season - 2) * 3 + 1, 1, date('Y')));
                $end_time = $timestamp_flag ? mktime(23, 59, 59, ($season - 1) * 3, 1, date('Y')) : date('Y-m-t H:i:s', mktime(23, 59, 59, ($season - 1) * 3, 1, date('Y')));
                break;
            case '11':
                //本年
                $start_time = $timestamp_flag ? strtotime(date('Y-01-01 00:00:00')) : date('Y-01-01 00:00:00');
                $end_time = $timestamp_flag ? strtotime(date('Y-12-31 23:59:59')) : date('Y-12-31 23:59:59');
                break;
            case '12':
                //上年
                $start_time = $timestamp_flag ? strtotime(date('Y-01-01 00:00:00', strtotime('-1 year'))) : date('Y-01-01 00:00:00', strtotime('-1 year'));
                $end_time = $timestamp_flag ? strtotime(date('Y-12-31 23:59:59', strtotime('-1 year'))) : date('Y-12-31 23:59:59', strtotime('-1 year'));
                break;
            case '13':
                //近一个月
                $start_time = $timestamp_flag ? strtotime('-1 month') : date('Y-m-d H:i:s', strtotime('-1 month'));
                $end_time = $timestamp_flag ? time() : date("Y-m-d H:i:s");
                break;
            case '14':
                //近三个月
                $start_time = $timestamp_flag ? strtotime('-3 month') : date('Y-m-d H:i:s', strtotime('-3 month'));
                $end_time = $timestamp_flag ? time() : date("Y-m-d H:i:s");
                break;
            default :
                //默认今天
                $start_time = $timestamp_flag ? strtotime(date("Y-m-d 00:00:00")) : date("Y-m-d 00:00:00");
                $end_time = $timestamp_flag ? time() : date("Y-m-d H:i:s");
                break;
        }

        return [
            'start_time' => $start_time,
            'end_time' => $end_time,
        ];
    }



}

